package control;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.AbstractAction;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

@SuppressWarnings("serial")
public abstract class AbstractTableAction extends AbstractAction
		implements
			KeyListener,
			ListSelectionListener,
			MouseListener {
	protected JTable table;

	public AbstractTableAction(String name, Icon icon, JTable table) {
		super(name, icon);
		this.table = table;
		setEnabled(false);
	}

	@Override
	public abstract void actionPerformed(ActionEvent e);

	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyChar() == '\n') {
			e.consume();
			actionPerformed(new ActionEvent(e.getSource(), e.getID(), null));
		}
	}

	@Override
	public void keyReleased(KeyEvent e) {
	}

	@Override
	public void keyTyped(KeyEvent e) {
	}

	@Override
	public void valueChanged(ListSelectionEvent e) {
		Integer selectedAmount = table.getSelectedRowCount();
		setEnabled(selectedAmount > 0);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if (e.getClickCount() == 2 && !e.isConsumed()) {
			e.consume();
			actionPerformed(new ActionEvent(e.getSource(), e.getID(), null));
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
	}

	@Override
	public void mouseExited(MouseEvent e) {
	}

	@Override
	public void mousePressed(MouseEvent e) {
	}

	@Override
	public void mouseReleased(MouseEvent e) {
	}

}
